package com.web.controller;


import com.domain.system.Module;
import com.domain.system.User;
import com.service.system.ModuleService;
import com.service.system.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController extends BaseController{

    @Autowired
    private HttpSession session;
    @Autowired
    private ModuleService moduleService;



	@RequestMapping("/login")
	public String login(String email,String password) {
        if (StringUtils.isBlank(email) || StringUtils.isBlank(password)) {
            request.setAttribute("error", "用户名或密码不能为空");
            return "forward:login.jsp";
        }

        try{

            //通过shiro进行登录
            Subject subject = SecurityUtils.getSubject();//首先从安全管理器里获取subject主体
            UsernamePasswordToken upToken = new UsernamePasswordToken(email, password);//传入参数
            //调用subject.login方法进行登录,login方法中进行了 身份认证 和 密码比较;
            // 密码不匹配时会抛出异常,用try...catch抓取
            subject.login(upToken);
            //登录成功后, 获取User对象 和 拥有的Modules
            User user = (User) subject.getPrincipal();

            if (user == null) {
                request.setAttribute("error", "用户名不存在");
                return "forward:login.jsp";
            }else{
                //将登录的用户放入session域
                session.setAttribute("loginUser", user);

                //动态展示菜单侧边栏,根据moduleService进行查询
                List<Module> modules = moduleService.findByUser(user);
                session.setAttribute("modules", modules);
                return "home/main";
            }

        }catch (Exception e){
            request.setAttribute("error", "用户名或密码错误");
            return "forward:login.jsp";
        }
	}

    //退出
    @RequestMapping(value = "/logout",name="用户登出")
    public String logout(){
        SecurityUtils.getSubject().logout();   //shiro登出
        return "forward:login.jsp";
    }

    @RequestMapping("/home")
    public String home(){
	    return "home/home";
    }

}
